package com.chendechao.model_home.ui.recommend

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chendechao.model_home.R
import com.chendechao.model_home.databinding.HomeVideoCardItemLayoutBinding
import com.chendechao.model_home.model.RecommendMutilVideo
interface OnItemClickListener {
    fun onItemClick(item: RecommendMutilVideo)
}
class RecommendAdapter(private val listener: RecommendFragment) : ListAdapter<RecommendMutilVideo,RecommendAdapter.RecommendViewHolder>(DiffCallback()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecommendViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = HomeVideoCardItemLayoutBinding.inflate(inflater,parent,false)
        return RecommendViewHolder(binding)
    }

    override fun onBindViewHolder(holder: RecommendViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item,listener)

    }
    class RecommendViewHolder(private val binding: HomeVideoCardItemLayoutBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: RecommendMutilVideo, listener: OnItemClickListener) {
            // 在这里绑定数据到视图
            // 例如：binding.videoTitle.text = item.title
            binding.videoTitle.text = item.toutiaolvideotext
            binding.videoInfo.text = item.favoritecount.toString()
            // 使用 Glide 加载图片
            Glide.with(binding.root.context)
                .load(item.videomainimag) // 假设 item.thumbnailUrl 是图片的 URL
                .placeholder(R.drawable.item_image) // 可选：加载过程中的占位符
                .error(com.example.mine.R.drawable.ic_launcher_background) // 可选：加载失败时的图片
                .into(binding.videoThumbnail) // 确保 videoThumbnail 是布局文件中的 ImageView 的 id

            binding.root.setOnClickListener {
                listener.onItemClick(item)
            }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<RecommendMutilVideo>() {
        override fun areItemsTheSame(
            oldItem: RecommendMutilVideo,
            newItem: RecommendMutilVideo
        ): Boolean {
            return   oldItem == newItem
        }

        override fun areContentsTheSame(
            oldItem: RecommendMutilVideo,
            newItem: RecommendMutilVideo
        ): Boolean {
            return   oldItem == newItem
        }

    }


}